package controllers

import (
	"time"
	"errors"
	"net/url"
	"net/http"
	"git.oschina.net/YPTArch/auth/sys/logs"
	"git.oschina.net/YPTArch/auth/models"
	"git.oschina.net/YPTArch/auth/sys/config"
	"strings"
)


const (
	USER = "user:"
	REFRESH = "refresh:"
)


//从url的参数中获取token
func getRawQueryToken(raw string) (string, error)  {

	getParams, err := url.ParseQuery(raw)
	if err != nil {
		logs.Logger.Error("get url token err:"+err.Error())
		return "", errors.New("验证登录URL参数格式不正确！")
	}

	var token string
	//如果不存在则返回空字符串
	if _, ok := getParams["token"]; !ok  {
		return "", nil
	}

	//存在但是数量不是一个，那么返回错误
	if len(getParams["token"]) != 1 {
		return "", errors.New("验证登录token数量不正确！")
	}else {
		token = getParams["token"][0]
	}

	return token, nil
}

//从header 中获取token
func getHeaderToken(r *http.Request) (string, error)   {

	//header 中不存在
	if _, ok := r.Header["Token"]; !ok {
		return "", nil
	}

	var token string
	//存在但是数量不是一个，那么返回错误
	if len(r.Header["Token"]) != 1 {
		return "", errors.New("验证登录token数量不正确！")
	}else {
		token = r.Header["Token"][0]
	}

	return token, nil
}


//保存token和刷新token
func saveTokenAndRefresh(user *models.User, IsGenRefresh bool) (generateTokenResponse models.GenerateTokenResponse, err error) {

	//存入redis中字段
	authUser := map[string]string{
		//"Token":token,
		//"Expiration":strconv.Itoa(config.Conf.Expiration),
		//"Refresh":refresh,
		//"RefreshExpiration":strconv.Itoa(config.Conf.RefreshExpiration),
		"UserId":user.UserId,
		"UserPwd":user.UserPwd,
		"UserName":user.UserName,
		"UserPhone":user.UserPhone,
		"UserEmail":user.UserEmail,
	}

	//------ token 生成部分 ------
	tokenTime := time.Now()
	//加密字段：用户id|时间戳
	encryptToken := user.UserId + "|" + time.Now().Format("2006-01-02 15:04:05")
	//生成token
	token, err := models.GenerateToken(encryptToken)
	if err != nil {
		logs.Logger.Error("Generatetoken() err:"+err.Error())
		return
	}

	//保存token
	err = save(USER + user.UserId, authUser, config.Conf.Expiration)
	if err != nil {
		return
	}



	//如果需要生成刷新token
	var refreshTime time.Time
	var refresh string
	if IsGenRefresh {
		refreshTime = time.Now()
		encryptRefresh := encryptToken + "|" + "Refresh"
		//生成
		refresh, err = models.GenerateToken(encryptRefresh)
		if err != nil {
			logs.Logger.Error("Generatetoken() err:"+err.Error())
			return
		}

		//保存刷新token
		err = save(REFRESH+refresh, authUser, config.Conf.RefreshExpiration)
		if err != nil {
			return
		}
	}


	//返回结构字段
	generateTokenResponse = models.GenerateTokenResponse{
		Access:token,
		AccessCreateAt:tokenTime,
		AccessExpiresIn:time.Duration(int64(config.Conf.Expiration)),
		Refresh:refresh,
		RefreshCreateAt:refreshTime,
		RefreshExpiresIn:time.Duration(int64(config.Conf.RefreshExpiration)),
	}


	return
}


//保存用户
func save(name string, authUser map[string]string, expiration int) error {

	//保存
	err := models.Save(name, authUser)
	if err != nil {
		logs.Logger.Error("Save err:" + err.Error())
		return err
	}

	//增加过期时间
	err = models.Delay(name, expiration)
	if err != nil {
		logs.Logger.Error("SetExpire err:" + err.Error())
		return err
	}

	return nil
}

//解析token
func parsingToken(tokenstring string) (uid string, err error)  {

	var token string
	token, err = models.ParsingToken(tokenstring)
	if err != nil {
		logs.Logger.Error("validate validateHandler err:"+err.Error())
		return
	}

	spliteString := strings.Split(token, "|")
	if len(spliteString) < 2 {
		logs.Logger.Error("validate validateHandler Split err:"+err.Error())
		return
	}

	uid = spliteString[0]
	return
}
